/*
 * @lc app=leetcode.cn id=2 lang=cpp
 *
 * [2] 两数相加
 */

#include <algorithm>
struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};
// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
  public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
    {
        int multi = 1;
        int add = 0;
        int overflow = 0;

        ListNode *new_head = new ListNode;
        ListNode *tmp = new_head;
        new_head->next = nullptr;

        while (l1 || l2) {
            ListNode *node = new ListNode;
            node->next = nullptr;
            if (l1 && l2) {
                add = l1->val + l2->val + overflow;
                overflow = add / 10;
                node->val = (add % 10);
                tmp->next = node;
                tmp = node;
                l1 = l1->next;
                l2 = l2->next;
            } else if (l1) {
                add = l1->val + overflow;
                overflow = add / 10;
                node->val = (add % 10);
                tmp->next = node;
                tmp = node;
                l1 = l1->next;
            } else if (l2) {
                add = l2->val + overflow;
                overflow = add / 10;
                node->val = (add % 10);
                tmp->next = node;
                tmp = node;
                l2 = l2->next;
            }
        }

        if (overflow) {
            ListNode *node = new ListNode;
            node->next = nullptr;
            node->val = overflow;
            tmp->next = node;
        }

        return new_head->next;
    }
};
// @lc code=end
